<template>
    <div style=" position: relative;">
        <el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 360px;" v-model="findCustomersPages_data.find"
                        placeholder="请输入客户名称电话、单位名称、负责人姓名电话" clearable prefix-icon="User" />

                   <el-select style="margin-left: 20px;width:130px" v-model="findCustomersPages_data.isServiceMan"
                        placeholder="是否是推广员" clearable>
                        <el-option v-for="item in isServiceMan_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>

                    <el-select style="margin-left: 20px;width:130px" v-model="findCustomersPages_data.cusRole"
                        placeholder="客户角色" clearable>
                        <el-option v-for="item in cusRole_list" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>

                    <el-select style="margin-left: 20px;width:130px" v-model="findCustomersPages_data.companyRole"
                        placeholder="单位角色" clearable>
                        <el-option v-for="item in companyRole_list.value" :key="item.id" :label="item.text"
                            :value="item.id" />
                    </el-select> 

                   <el-input style="margin-left: 20px;width: 200px;" v-model="findCustomersPages_data.recPhone"
                        placeholder="请输入推荐人手机号" clearable prefix-icon="Iphone" />
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <!-- <el-button @click="add_user_btn" type="primary" icon="SuccessFilled">添加客户</el-button>
                    <el-button @click="up_user_btn" type="primary" icon="WarningFilled">修改客户</el-button>
                    <el-button @click="de_user_btn" type="primary" icon="CircleCloseFilled">删除客户</el-button> -->
                    <el-button @click="set_user_btn" type="warning" icon="Tools">设置为推广员</el-button>
                    <el-button @click="findPriceTemplatesNameCombo_off_btn" type="warning"
                        icon="Menu">客户价格配置</el-button>
                    <el-button @click="set_ment_btn" type="warning" icon="Tools">客户账单日设置</el-button>
                    <el-button @click="setHandTeamReward_btn" type="warning" icon="Tools">车队一级提成设置</el-button>
                    <el-button @click="setHandTravelReward_btn" type="warning" icon="Tools">旅行社一级提成设置</el-button>
                    <!-- <el-button @click="ex_user_btn" type="warning" icon="Share">导出</el-button> -->
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <!-- <template v-if="item.field == 'companyRole'" #="{ row, column, $index }">
                                {{ row.companyRole == 'TRAVEL_AGENCY' ? '旅行社' : row.companyRole == 'CAR_TEAM' ? '车队' :
                                    row.companyRole
                                        == 'RENT_COMPANY' ? '租赁公司' : '会务公司' }}

                            </template> -->
                            <template v-if="item.field == 'recRealName'" #="{ row, column, $index }">
                                {{ row.recRealName + '(' + row.recPhone + ')' }}

                            </template>
                            <template v-if="item.field == 'isServiceMan'" #="{ row, column, $index }">
                                {{ row.isServiceMan=='1'?'是':'否' }}

                            </template>

                            <!-- <template v-if="item.field == 'businessNumUrl'" #="{ row, column, $index }">
                                <el-image style="width: 95px; height: 95px" :preview-teleported="true"
                                    :preview-src-list="[ImageUrl + row.businessNumUrl]"
                                    :src="row.businessNumUrl ? ImageUrl + row.businessNumUrl : ''" fit="cover">
                                    <template #error>
                                        <div>
                                            <el-icon style="width: 95px; height:95px"><icon-picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>

                            </template> -->

                            <!-- <template v-if="item.field == 'busLicenseUrl'" #="{ row, column, $index }">
                                <el-image style="width: 95px; height: 95px" :preview-teleported="true"
                                    :preview-src-list="[ImageUrl + row.busLicenseUrl]"
                                    :src="row.busLicenseUrl ? ImageUrl + row.busLicenseUrl : ''" fit="cover">
                                    <template #error>
                                        <div>
                                            <el-icon style="width: 95px; height: 95px"><icon-picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </template> -->

                            <template v-if="item.field == 'isServiceMan'" #="{ row, column, $index }">
                                <span>{{ row.isServiceMan == '0' ? '否' : '是' }}</span>
                            </template>
                            <template v-if="item.field == 'handTeamReward'" #="{ row, column, $index }">
                                <span>{{ row.isServiceMan == '0' ? '否' : '是' }}</span>
                            </template>
                            <template v-if="item.field == 'handTravelReward'" #="{ row, column, $index }">
                                <span>{{ row.isServiceMan == '0' ? '否' : '是' }}</span>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="findCustomersPages_data.page.pageNum"
                    v-model:page-size="findCustomersPages_data.page.pageSize" :page-sizes="[20, 30, 50, 100]"
                    :background="true" layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
        <!-- 弹窗 -->
        <div>
            <!-- 表格筛选 -->
            <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
                <el-icon @click="icon_btn" :size="20">
                    <Setting />
                </el-icon>
                <div v-show="icon_off"
                    style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                    <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                        <div>
                            <el-button-group style="display: flex; ">
                                <el-tooltip effect="dark" placement="bottom">
                                    <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                    <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                                </el-tooltip>
                                <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                                <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                            </el-button-group>
                            <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                                <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                    :key="item.field" v-model="item.off" :label="item.label" border>
                                </el-checkbox>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
            <!-- 添加修改客户 -->
            <el-dialog style="margin-top:5vh" v-model="add_user_off" :title="title" width="40%"
                :close-on-click-modal='false'>
                <el-form :model="add_user_data" label-width="130px" ref="add_ref" :rules="add_rules" label-suffix="：">
                    <el-form-item prop="companyRole" label="单位角色" :required="true">
                        <el-select @change="companyRole_change" v-model="add_user_data.companyRole" placeholder="单位角色"
                            clearable>
                            <el-option v-for="item in companyRole_list.value" :key="item.id" :label="item.text"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="companyName" label="单位名称" :required="true">
                        <el-input v-model="add_user_data.companyName" placeholder="请输入单位名称" maxlength="15"
                            show-word-limit />
                    </el-form-item>
                    <el-form-item prop="realName" label="客户姓名" :required="true">
                        <el-input v-model="add_user_data.realName" placeholder="请输入客户姓名" />
                    </el-form-item>
                    <el-form-item prop="loginPhone" label="客户电话" :required="true">
                        <el-input type="number" v-model="add_user_data.loginPhone" placeholder="请输入客户电话" />
                    </el-form-item>
                    <el-form-item label="拥有车型" :required="false">
                        <el-select v-model="add_user_data.seats" multiple collapse-tags collapse-tags-tooltip clearable
                            placeholder="请选择车型" style="width: 220px;">
                            <el-option label="5座" value="5"></el-option>
                            <el-option label="7座" value="7"></el-option>
                            <el-option label="9座" value="9"></el-option>
                            <el-option label="12座" value="12"></el-option>
                            <el-option label="14座" value="14"></el-option>
                            <el-option label="17座" value="17"></el-option>
                            <el-option label="30座" value="30"></el-option>
                            <el-option label="39座" value="39"></el-option>
                            <el-option label="49座" value="49"></el-option>
                            <el-option label="55座" value="55"></el-option>

                        </el-select>
                    </el-form-item>
                    <el-form-item label="单位负责人" :required="false">
                        <el-input v-model="add_user_data.headName" placeholder="请输入单位负责人" />
                    </el-form-item>
                    <el-form-item label="负责人电话" :required="false">
                        <el-input type="number" v-model="add_user_data.headPhone" placeholder="请输入单位负责人电话" />
                    </el-form-item>
                    <el-form-item label="身份证号" :required="false">
                        <el-input type="number" v-model="add_user_data.idCard" placeholder="请输入身份证号" />
                    </el-form-item>
                    <el-form-item label="服务内容" :required="false">
                        <el-input show-word-limit maxlength="30" type="textarea" v-model="add_user_data.content" />
                    </el-form-item>
                    <el-form-item label="营业执照照片" :required="false">
                        <el-upload class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                            :data="{ ftype: 'BUSINESS_IMG', files: rawFile_list }" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload" :show-file-list="false">
                            <img v-if="add_user_data.busLicenseUrl" :src="ImageUrl + add_user_data.busLicenseUrl"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="经营许可证照片" :required="false">
                        <el-upload class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                            :data="{ ftype: 'BUSINESS_IMG', files: rawFile_list_2 }" :on-success="handleAvatarSuccess_2"
                            :before-upload="beforeAvatarUpload_2" :show-file-list="false">
                            <img v-if="add_user_data.businessNumUrl" :src="ImageUrl + add_user_data.businessNumUrl"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="单位地址" :required="false">
                        <el-input @click="map_off_btn" v-model="add_user_data.address" placeholder="请选择单位地址" />
                    </el-form-item>

                    <el-form-item label="推荐人用户id" :required="false">
                        <el-select v-model="add_user_data.recUserId" filterable remote reserve-keyword
                            placeholder="请输入推荐人姓名或电话" remote-show-suffix :remote-method="remoteMethod"
                            :loading="loading">
                            <el-option v-for="item in recUserId_list" :key="item.userId"
                                :label="recUserId_list_api(item)" :value="item.userId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注" :required="false">
                        <el-input show-word-limit maxlength="30" type="textarea" v-model="add_user_data.note" />
                    </el-form-item>

                </el-form>
                <el-button style="margin-left:30vw" @click="form_ok_btn(add_ref)" type="primary">确认提交</el-button>
            </el-dialog>

            <!-- 地图弹窗 -->
            <el-dialog style="margin-top:10vh;height:80vh;overflow: hidden;" v-model="map_off" title="单位地址:" width="80%"
                :close-on-click-modal='false'>
                <div id="myMap" style="height: 65vh; width: 100%">
                    <div class="map_input">
                        <el-input @input="map_change" id='tipinput' style="width:40%" v-model="map_address"
                            placeholder="请输入单位地址">
                            <template #prepend>单位地址:</template>
                        </el-input>
                        <el-button @click="map_ok_btn" type="primary">确认</el-button>
                    </div>
                    <div v-if="map_address_list.length > 0" class="map_input">
                        <div style="width:40%;background:#fff;margin-left:20px;padding: 10px;font-weight: 700;">
                            <div @click="map_list_btn(item)" class="div_bg" v-for="(item, index) in map_address_list"
                                :key="index" style="margin-top: 10px;">
                                {{ item.district }}-{{ item.address }}-{{ item.name }}
                            </div>
                        </div>
                    </div>
                </div>
            </el-dialog>

            <!-- 客户价格配置 -->
            <el-dialog v-model="findPriceTemplatesNameCombo_off" title="客户价格配置：" width="25%">
                <div>
                    <el-select style="width:100%" v-model="findPriceTemplatesNameCombo_data" placeholder="请选择价格配置"
                        size="large">
                        <el-option v-for="item in findPriceTemplatesNameCombo_list" :key="item.id"
                            :label="item.templates_name" :value="item.id" />
                    </el-select>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="findPriceTemplatesNameCombo_off = false">取消</el-button>
                        <el-button type="primary" @click="setPriceTemplate_btn">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 客户账单,还款,催收日设置 -->
            <el-dialog v-model="set_ment_off" title="客户账单日设置：" width="40%">
                <div>
                    <el-form :model="set_ment_data" label-width="110px" label-suffix="：">
                        <el-form-item label="账单日" :required="false">
                            <el-input oninput="if(value.length>2)value=value.slice(0,2)" type="number"
                                style="width:220px" v-model="set_ment_data.billDay" placeholder="请输入账单日，如：21" />
                        </el-form-item>
                        <el-form-item label="最后还款日" :required="false">
                            <el-input type="number" oninput="if(value.length>2)value=value.slice(0,2)"
                                style="width:220px" v-model="set_ment_data.lastRepaymentDay"
                                placeholder="请输入最后还款日，如：21" />
                        </el-form-item>
                        <div style="display: flex;">
                            <el-form-item label="催收日" :required="false">
                                <el-input oninput="if(value.length>2)value=value.slice(0,2)" style="width:220px"
                                    type="number" v-model="lastRepaymentDay_data" placeholder="请输入催收日，如：21" />
                                <el-button style="margin-left:20px" @click="lastRepaymentDay_data_btn" type="primary"
                                    icon="Plus">添加</el-button>
                            </el-form-item>
                        </div>
                        <div v-if="lastRepaymentDay_data_list.length > 0">
                            <el-tag style="margin-left:10px;margin-top:5px" v-for="item in lastRepaymentDay_data_list"
                                :key="item" class="mx-1" closable type="danger" @close="close_btn(item)">
                                催收日:{{ item }}号
                            </el-tag>
                        </div>

                        <div style="display: flex;margin-top:30px;">
                            <el-form-item label="还款提醒日" :required="false">
                                <el-input oninput="if(value.length>2)value=value.slice(0,2)" style="width:220px"
                                    type="number" v-model="remindRepaymentDay_data" placeholder="请输入还款提醒日，如：21" />
                                <el-button style="margin-left:20px" @click="remindRepaymentDay_btn" type="primary"
                                    icon="Plus">添加</el-button>
                            </el-form-item>
                        </div>
                        <div v-if="remindRepaymentDay_data_list.length > 0">
                            <el-tag style="margin-left:10px;margin-top:5px" v-for="item in remindRepaymentDay_data_list"
                                :key="item" class="mx-1" closable type="danger" @close="close_btn2(item)">
                                还款提醒日:{{ item }}号
                            </el-tag>
                        </div>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="set_ment_off = false">取消</el-button>
                        <el-button type="primary" @click="remindRepaymentDay_ok_btn">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>

             <!-- 设置推广员 -->
        <el-dialog style="margin-top:5vh" v-model="set_user_data.off" title="推广员设置" width="30%"
        :close-on-click-modal='false'>
        <div> 推广员设置开关:
            <el-switch v-model="set_user_data.isServiceMan" active-color="#13ce66" inactive-color="#DCDFE6">
            </el-switch>
        </div>

        <el-button style="margin-left:23vw" type="primary" @click="set_userBtn()">确 定</el-button>
    </el-dialog>

       <!-- 车队一级提出设置 -->
       <el-dialog style="margin-top:5vh" v-model="setHandTeamReward_data.off" title="车队一级提成设置" width="30%"
       :close-on-click-modal='false'>
       <div> 车队一级提成设置开关:
           <el-switch v-model="setHandTeamReward_data.handTeamReward" active-color="#13ce66" inactive-color="#DCDFE6">
           </el-switch>
       </div>

       <el-button style="margin-left:23vw" type="primary" @click="setHandTeamRewardBtn()">确 定</el-button>
   </el-dialog>
  <!-- 旅行社一级提出设置 -->
  <el-dialog style="margin-top:5vh" v-model="setHandTravelReward_data.off" title="旅行社一级提成设置" width="30%"
  :close-on-click-modal='false'>
  <div> 旅行社一级提成设置开关:
      <el-switch v-model="setHandTravelReward_data.handTeamReward" active-color="#13ce66" inactive-color="#DCDFE6">
      </el-switch>
  </div>

  <el-button style="margin-left:23vw" type="primary" @click="setHandTravelRewardBtn()">确 定</el-button>
</el-dialog>

   
        </div>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import CircularJSON from 'circular-json'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    findCustomersPages, getFileType, findComboCusList, addCustomers, modifyCustomers, delCustomers, setServiceMan,
    findPriceTemplatesNameCombo, setPriceTemplate, expCutomers, setBillRepaymentHurryDay, adupPrivateSet, getPrivateSetList,
    setHandTravelReward, setHandTeamReward
} from '@/api/customer_list.js'
import { companyRole_data, ImageUrl, FileType, ImageUrl_upload } from '@/utils/common.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { GET_TOKEN } from '@/utils/token.js'
import AMapLoader from "@amap/amap-jsapi-loader"
import { securityJsCode, key } from '@/utils/common.js'
import * as XLSX from 'xlsx';
onMounted(async () => {
    companyRole_list.value = companyRole_data
    let custom_list = JSON.parse(localStorage.getItem('custom_list'))
    if (custom_list) {
        findCustomersPages_data.companyRole = custom_list.companyRole
        findCustomersPages_data.cusRole = custom_list.cusRole
        findCustomersPages_data.find = custom_list.find
        findCustomersPages_data.isServiceMan = custom_list.isServiceMan
        findCustomersPages_data.recPhone = custom_list.recPhone
    }

    getPrivateSetList({
        find: '客户列表',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    await findCustomersPages_api()

})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '所属单位', field: 'companyName', width: 200, off: true },
    { label: '姓名', field: 'realName', width: 200, off: true },
    { label: '电话', field: 'loginPhone', width: 200, off: true },
    { label: '客户价格配置', field: 'templatesName', width: 200, off: true },
    { label: '账单日', field: 'billDay', width: 100, off: true },
    { label: '最后还款日', field: 'lastRepaymentDay', width: 100, off: true },
    { label: '催收日', field: 'hurryRepaymentDay', width: 100, off: true },
    { label: '还款提醒日', field: 'remindRepaymentDay', width: 100, off: true },
    // { label: '单位角色', field: 'companyRole', width: 110, off: true },
    // { label: '单位负责人姓名', field: 'headName', width: 125, off: true },
    // { label: '单位负责人电话', field: 'headPhone', width: 125, off: true },
    // { label: '单位经营许可证图片', field: 'businessNumUrl', width: 155, off: true },
    // { label: '单位工商营业执照图片', field: 'busLicenseUrl', width: 165, off: true },
    // { label: '推荐人姓名', field: 'recRealName', width: 100, off: true },
    // { label: '推荐人手机号', field: 'recPhone', width: 120, off: true },
    { label: '是否是推广员', field: 'isServiceMan', width: 110, off: true },
    { label: '车队一级提成设置', field: 'handTeamReward', width: 150, off: true },
    { label: '旅行一级提成设置', field: 'handTravelReward', width: 150, off: true },
    { label: '客户推荐人', field: 'recRealName', width: 200, off: true },
    { label: '客户备注', field: 'note', width: 200, off: true },
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {

    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))

}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '客户列表',
        tbNum: "custom_list",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion




//#region 是否是推广人
const isServiceMan_list = reactive([
    {
        value: '0',
        label: '否',
    },
    {
        value: '1',
        label: '是',
    },
])
//#endregion

//#region 客户角色
const cusRole_list = reactive([
    {
        value: 'COMPANY',
        label: '单位',
    },
    {
        value: 'PERSONAL',
        label: '个人',
    },
])
//#endregion

//#region 单位角色
const companyRole_off = ref(false)
const companyRole_list = reactive([])
const companyRole_change = (e) => {
    if (e == 'CAR_TEAM') {
        companyRole_off.value = true
    } else {
        companyRole_off.value = false
    }
}
//#endregion


//#region 搜索
const search_btn = () => {
    if (findCustomersPages_data.recPhone && findCustomersPages_data.recPhone.length != 11) {
        return ElMessage({
            message: '请输入正确的手机号',
            type: 'warning',
        })
    }
    localStorage.setItem('custom_list', CircularJSON.stringify(findCustomersPages_data))
    findCustomersPages_api()
}
//#endregion


//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion

//#region 分页列表
const list_data = ref([]) // 表格数据
const total = ref(0)
const findCustomersPages_data = reactive({
    companyRole: '', // 单位角色
    cusRole: '', // 客户角色：单位【COMPANY】个人【PERSONAL】
    find: '', // 客户名称电话、单位名称、负责人姓名电话
    isServiceMan: '', // 是否是推广员：0 否 1是
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    recPhone: '', // 推荐人手机号
})
// 页面数据
const findCustomersPages_api = () => {
    findCustomersPages(findCustomersPages_data).then(res => {
        if (res.code == 1) {
            list_data.value = res.data.list
            total.value = res.data.total
        }
    })
}
// 分页器跳转页面
const current_change_btn = () => {
    findCustomersPages_api()
}

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    findCustomersPages_data.page.pageNum = 1
    findCustomersPages_api()
}
//#endregion

const title = ref('') // 添加修改客户弹窗title

//#region 添加客户
const add_user_off = ref(false)
const add_user_data = reactive({
    address: '', // 详细地址
    busLicenseUrl: '', //营业执照照片url
    businessNumUrl: '', // 经营许可证照片url
    companyName: '', // 单位名称
    companyRole: '', // 单位角色
    headName: '', // 单位负责人姓名
    headPhone: '', // 单位负责人电话
    lngLat: '', // 详细地址坐标
    loginPhone: '', //客户电话
    note: '', // 备注
    realName: '', // 客户姓名
    recUserId: '', // 推荐人用户id
    idCard: '',
    content: "",
    seats: '',
})
const add_user_btn = () => {
    add_user_data.address = ''
    add_user_data.busLicenseUrl = ''
    add_user_data.businessNumUrl = ''
    add_user_data.companyName = ''
    add_user_data.companyRole = ''
    add_user_data.headName = ''
    add_user_data.headPhone = ''
    add_user_data.lngLat = ''
    add_user_data.loginPhone = ''
    add_user_data.note = ''
    add_user_data.realName = ''
    add_user_data.recUserId = ''
    add_user_data.idCard = ''
    add_user_data.content = ''
    add_user_data.seats = ''
    title.value = '添加客户：'
    add_user_off.value = true

}

// 上传营业执照照片
const rawFile_list = ref([])
const handleAvatarSuccess = (response, uploadFile) => {
    add_user_data.busLicenseUrl = response.data.file.url
}

const beforeAvatarUpload = (rawFile) => {
    rawFile_list.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list.value.push(rawFile)
    return true

}

// 经营许可证照片url
const rawFile_list_2 = ref([])
const handleAvatarSuccess_2 = (response, uploadFile) => {
    add_user_data.businessNumUrl = response.data.file.url
}

const beforeAvatarUpload_2 = (rawFile) => {
    rawFile_list_2.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }
    rawFile_list_2.value.push(rawFile)
    return true

}


// 地图
const myMap = ref('')
const geolocation = ref('') // 定位
const map_address = ref('')
const map_lngLat = ref('')
const map_address_list = ref([])
const marker = ref('')
const map_off = ref(false)
const map_off_btn = () => {
    map_off.value = true
    // 地图
    window._AMapSecurityConfig = {
        securityJsCode: securityJsCode,
    }
    // 首次加载
    AMapLoader.load({
        key: key,
        version: '2.0',
        plugins: ['AMap.Driving', 'AMap.Geolocation', 'AMap.Scale', 'AMap.AutoComplete', 'AMap.PlaceSearch'],
    }).then((AMap) => {
        // 初始化-地图对象
        myMap.value = new AMap.Map('myMap', { zoom: 10, center: [104.065861, 30.657401] });
        myMap.value.addControl(new AMap.Scale())
        geolocation.value = new AMap.Geolocation({ //定位
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            convert: true, //自动偏移坐标 为高德坐标，默认：true
            timeout: 5000, //超过5秒后停止定位，默认：无穷大
            buttonPosition: 'RB', //定位按钮停靠位置
            showMarker: true, //定位成功在位置显示点标记，默认：true
        })
        myMap.value.addControl(geolocation.value)
        geolocation.value.getCurrentPosition((status, result) => {
            console.log('定位getCurrentPosition', status, result);
            if (status == 'complete') {
                console.log('定位信息', result);
            } else {
                console.log('定位出错', result);
            }
        })



    }).catch(err => { console.log('高德地图加载失败：', err); });
}
const map_change = () => {
    let autoOptions = {
        city: '全国'
    }
    var autoComplete = new AMap.Autocomplete(autoOptions);
    autoComplete.search(map_address.value, function (status, result) {
        // 搜索成功时，result即是对应的匹配数据
        map_address_list.value = result.tips.slice(0, 5)
    })
}

const map_list_btn = (e) => {
    map_address.value = e.district + '-' + e.address + '-' + e.name
    map_lngLat.value = e.location.lng + ',' + e.location.lat
    myMap.value.panTo([e.location.lng, e.location.lat]);
    if (marker.value) {
        myMap.value.remove(marker.value);
    }
    myMap.value.setFitView();
    marker.value = new AMap.Marker({
        map: myMap.value,
        position: [e.location.lng, e.location.lat],
    });
    myMap.value.setFitView();
    myMap.value.add(marker.value);


}
const map_ok_btn = (e) => {
    add_user_data.address = map_address.value
    add_user_data.lngLat = map_lngLat.value
    map_off.value = false

}

// 推荐人id
const loading = ref(false)
const recUserId_list = ref([])
const recUserId_list_api = (item) => {


    if (item.realName != null && item.companyName != null) {
        return item.loginPhone + '-' + item.realName + '-' + item.companyName
    } else if (item.companyName == null && item.realName != null) {
        return item.loginPhone + '-' + item.realName
    } else if (item.companyName != null && item.realName == null) {
        return item.loginPhone + '-' + item.companyName
    } else {
        return item.loginPhone
    }


}
const remoteMethod = (query) => {
    if (query) {
        loading.value = true
        findComboCusList({
            find: query,
            page: {
                pageNum: '1',
                pageSize: '999'
            }
        }).then(res => {
            loading.value = false
            recUserId_list.value = res.data.list

        })

    } else {
        recUserId_list.value = []
    }
}

// 添加和修改的提交
const add_ref = ref()
const form_ok_btn = (add_ref) => {
    if (!add_ref) return
    if (companyRole_off.value) {
        if (!add_user_data.seats) {
            return ElMessage({
                message: '请选择拥有车型',
                type: 'warning',
            })
        }

    }

    add_ref.validate(async (valid, fields) => {
        console.log(title.value)
        if (valid) {
            const loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })



            if (title.value == '添加客户：') {
                if (add_user_data.seats) {
                    add_user_data.seats = add_user_data.seats.join(',')
                }

                await addCustomers(add_user_data).then(res => {
                    if (res.code == 1) {
                        add_user_off.value = false
                        findCustomersPages_api()
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            } else {
                if (add_user_data.seats) {
                    add_user_data.seats = add_user_data.seats.join(',')
                }
                await modifyCustomers(add_user_data).then(res => {
                    if (res.code == 1) {
                        add_user_off.value = false
                        findCustomersPages_api()
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }






        } else {
            console.log('登录表单验证不通过!', fields)
        }
    })
}
const add_rules = reactive({
    companyRole: [
        { required: true, message: '请选择单位角色', trigger: 'change' },

    ],
    companyName: [
        { required: true, message: '单位名称', trigger: 'change' },
    ],
    realName: [
        { required: true, message: '客户姓名', trigger: 'change' },
    ],
    loginPhone: [
        { required: true, message: '客户电话', trigger: 'change' },
        { min: 11, max: 11, message: '收输入11位数字的手机号', trigger: 'blur' },
    ],
})

//#endregion

//#region 修改客户

const up_user_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    add_user_data.address = table_list.value[0].address
    add_user_data.busLicenseUrl = table_list.value[0].busLicenseUrl
    add_user_data.businessNumUrl = table_list.value[0].businessNumUrl
    add_user_data.companyName = table_list.value[0].companyName
    add_user_data.companyRole = table_list.value[0].companyRole
    add_user_data.headName = table_list.value[0].headName
    add_user_data.headPhone = table_list.value[0].headPhone
    add_user_data.lngLat = table_list.value[0].lngLat
    add_user_data.loginPhone = table_list.value[0].loginPhone
    add_user_data.note = table_list.value[0].note
    add_user_data.realName = table_list.value[0].realName
    add_user_data.recUserId = table_list.value[0].regRecUserId
    add_user_data.userId = table_list.value[0].userId
    add_user_data.content = table_list.value[0].content
    add_user_data.seats = table_list.value[0].seats ? table_list.value[0].seats.split(',') : ''
    add_user_data.idCard = table_list.value[0].idCard
    title.value = '修改客户：'
    add_user_off.value = true
}
//#endregion

//#region 删除客户
const de_user_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    ElMessageBox.confirm(
        '是否确认删除客户?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delCustomers({
                userId: table_list.value[0].userId
            }).then(res => {
                if (res.code == 1) {
                    findCustomersPages_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

// 车队一级提出

const setHandTeamReward_data = ref({
    handTeamReward: false,
    userId: '',
    off: false
})
const setHandTeamReward_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    setHandTeamReward_data.value.handTeamReward = table_list.value[0].handTeamReward == '1'?true:false
    setHandTeamReward_data.value.off = true
}
const setHandTeamRewardBtn = () => {
    let ps = {
        handTeamReward: '',
        userId: '',
    }
    if (setHandTeamReward_data.value.handTeamReward) {
        ps.handTeamReward = 1
    } else {
        ps.handTeamReward = 0
    }
    ps.userId = table_list.value[0].userId
    setHandTeamReward(ps).then(res => {
        if (res.code == 1) {
            findCustomersPages_api()
            setHandTeamReward_data.value.off = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}
// 旅行社一级提出
// const setHandTravelReward_btn = () => {

//     if (table_list.value.length != 1) {
//         return ElMessage({
//             message: '请选择一条数据！',
//             type: 'warning',
//         })
//     }
//     ElMessageBox.confirm(
//         '确定客户能拿一级提成?',
//         {
//             confirmButtonText: '确认',
//             cancelButtonText: '取消',
//             type: 'warning',
//             distinguishCancelAndClose: 'true',
//         }
//     )
//         .then(() => {
//             setHandTravelReward({
//                 handTeamReward: '1',
//                 userId: table_list.value[0].userId
//             }).then(res => {
//                 if (res.code == 1) {
//                     findCustomersPages_api()
//                     return ElMessage({
//                         message: res.msg,
//                         type: 'success',
//                     })
//                 } else {
//                     return ElMessage({
//                         message: res.msg,
//                         type: 'warning',
//                     })
//                 }
//             })
//         })
//         .catch((e) => {
//             if (e == 'cancel') {
//                 ElMessage({
//                     type: 'warning',
//                     message: '取消成功',
//                 })
//             }

//         })


// }
const setHandTravelReward_data = ref({
    handTeamReward: false,
    userId: '',
    off: false
})
const setHandTravelReward_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    setHandTravelReward_data.value.handTravelReward = table_list.value[0].handTravelReward == '1'?true:false
    setHandTravelReward_data.value.off = true
}
const setHandTravelRewardBtn = () => {
    let ps = {
        handTeamReward: '',
        userId: '',
    }
    if (setHandTravelReward_data.value.handTeamReward) {
        ps.handTeamReward = 1
    } else {
        ps.handTeamReward = 0
    }
    ps.userId = table_list.value[0].userId
    setHandTravelReward(ps).then(res => {
        if (res.code == 1) {
            findCustomersPages_api()
            setHandTravelReward_data.value.off = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}
//#region 客户账单,还款,催收日设置
const set_ment_off = ref(false)
const set_ment_data = reactive({
    billDay: '',
    hurryRepaymentDay: '',
    lastRepaymentDay: '',
    remindRepaymentDay: '',
    userId: '',
})
const lastRepaymentDay_data = ref('')
const lastRepaymentDay_data_list = ref([])
const lastRepaymentDay_data_btn = () => {
    if (lastRepaymentDay_data.value > 31 || lastRepaymentDay_data.value < 1) {
        return ElMessage({
            message: '请输入1-31！',
            type: 'warning',
        })
    }
    lastRepaymentDay_data_list.value.push(lastRepaymentDay_data.value)
    lastRepaymentDay_data.value = ''
}
const close_btn = (e) => {
    let index = lastRepaymentDay_data_list.value.indexOf(e);
    if (index !== -1) {
        lastRepaymentDay_data_list.value.splice(index, 1);
    }
}

const remindRepaymentDay_data = ref('')
const remindRepaymentDay_data_list = ref([])
const remindRepaymentDay_btn = () => {
    if (remindRepaymentDay_data.value > 31 || remindRepaymentDay_data.value < 1) {
        return ElMessage({
            message: '请输入1-31！',
            type: 'warning',
        })
    }
    remindRepaymentDay_data_list.value.push(remindRepaymentDay_data.value)
    remindRepaymentDay_data.value = ''
}
const close_btn2 = (e) => {
    let index = remindRepaymentDay_data_list.value.indexOf(e);
    if (index !== -1) {
        remindRepaymentDay_data_list.value.splice(index, 1);
    }
}

const set_ment_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    set_ment_data.billDay = table_list.value[0].billDay
    set_ment_data.hurryRepaymentDay =table_list.value[0].hurryRepaymentDay
    set_ment_data.lastRepaymentDay = table_list.value[0].lastRepaymentDay
    set_ment_data.remindRepaymentDay = table_list.value[0].remindRepaymentDay
    set_ment_data.userId = ''
    lastRepaymentDay_data.value = ''
    lastRepaymentDay_data_list.value = table_list.value[0].hurryRepaymentDay.split(',')
    remindRepaymentDay_data.value = ''
    remindRepaymentDay_data_list.value =table_list.value[0].remindRepaymentDay.split(',')
    set_ment_data.userId = table_list.value[0].userId
    set_ment_off.value = true

}
const remindRepaymentDay_ok_btn = () => {
    set_ment_data.hurryRepaymentDay = lastRepaymentDay_data_list.value.join(',')
    set_ment_data.remindRepaymentDay = remindRepaymentDay_data_list.value.join(',')
    if (!set_ment_data.billDay) {
        return ElMessage({
            message: '请输入账单日！',
            type: 'warning',
        })
    } else if (!set_ment_data.hurryRepaymentDay) {
        return ElMessage({
            message: '请添加账单日！',
            type: 'warning',
        })
    } else if (!set_ment_data.lastRepaymentDay) {
        return ElMessage({
            message: '请输入最后还款日！',
            type: 'warning',
        })
    } else if (!set_ment_data.remindRepaymentDay) {
        return ElMessage({
            message: '请添加还款提醒日！',
            type: 'warning',
        })
    } else if (lastRepaymentDay_data.value) {
        return ElMessage({
            message: '催收日不为空，你先点击添加',
            type: 'warning',
        })
    } else if (remindRepaymentDay_data.value) {
        return ElMessage({
            message: '还款提醒日不为空，你先点击添加',
            type: 'warning',
        })
    }

    console.log(set_ment_data)
    setBillRepaymentHurryDay(set_ment_data).then(res => {
        set_ment_off.value = false
        if (res.code == 1) {
            findCustomersPages_api()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            findCustomersPages_api()
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}

//#endregion
//#region 设置为推广员

const set_user_data = ref({
    isServiceMan: false,
    userId: '',
    off: false
})
const set_user_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    set_user_data.value.isServiceMan = table_list.value[0].isServiceMan == '1'?true:false
    set_user_data.value.off = true
}
const set_userBtn = () => {
    let ps = {
        isServiceMan: '',
        userId: '',
    }
    if (set_user_data.value.isServiceMan) {
        ps.isServiceMan = 1
    } else {
        ps.isServiceMan = 0
    }
    ps.userId = table_list.value[0].userId
    setServiceMan(ps).then(res => {
        if (res.code == 1) {
            findCustomersPages_api()
            set_user_data.value.off = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}
//#endregion

//#region 客户价格配置
const findPriceTemplatesNameCombo_off = ref(false)
const findPriceTemplatesNameCombo_list = ref([])
const findPriceTemplatesNameCombo_data = ref('')
const findPriceTemplatesNameCombo_off_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    findPriceTemplatesNameCombo({ page: { pageNum: 1, pageSize: 999 } }).then(res => {
        if (res.code == 1) {
            findPriceTemplatesNameCombo_list.value = res.data.list
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
    findPriceTemplatesNameCombo_data.value =  Number(table_list.value[0].templatesInfoId )
    findPriceTemplatesNameCombo_off.value = true
}

const setPriceTemplate_btn = () => {
    setPriceTemplate({
        userId: table_list.value[0].userId,
        templatesInfoId: findPriceTemplatesNameCombo_data.value
    }).then(res => {
        if (res.code == 1) {
            findCustomersPages_api()
            findPriceTemplatesNameCombo_off.value = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}

//#endregion

//#region 导出

const ex_user_btn = () => {


    let ps = {
        cusRole: findCustomersPages_data.cusRole,
        find: findCustomersPages_data.find,
        isServiceMan: findCustomersPages_data.isServiceMan,
        recPhone: findCustomersPages_data.recPhone,
    }
    expCutomers(ps).then(res => {
        // ['编号', '用户姓名', '用户手机号', '单位名称', '单位角色', '单位负责人姓名', '单位负责人电话', '单位详细地址', '推荐人姓名', '推荐人手机号', '是否是推荐人', '用户备注', '添加时间'],

        if (res.code == 1) {
            const data = [
                ['用户姓名', '用户手机号', '单位名称', '单位角色', '单位负责人姓名', '单位负责人电话', '单位详细地址', '推荐人姓名', '推荐人手机号', '是否是推荐人', '用户备注', '添加时间'],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {
                    realName: res.data[i].realName,
                    loginPhone: res.data[i].loginPhone,
                    companyName: res.data[i].companyName,
                    companyRole: res.data[i].companyRole == 'TRAVEL_AGENCY' ? '旅行社' : res.data[i].companyRole == 'CAR_TEAM' ? '车队' : res.data[i].companyRole == 'RENT_COMPANY' ? '租赁公司' : '会务公司',
                    headName: res.data[i].headName,
                    headPhone: res.data[i].headPhone,
                    address: res.data[i].address,
                    recRealName: res.data[i].recRealName,
                    recPhone: res.data[i].recPhone,
                    isServiceMan: res.data[i].isServiceMan == '0' ? '否' : '是',
                    note: res.data[i].note,
                    addTime: res.data[i].addTime,

                }
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            // ws['!cols'][0] = [{ wch: 170 }];
            // ws['!cols'][1] = [{ wch: 170 }]; //如果要将第二列的宽度设置为 30
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '客车帮服务后台系统管理-客户列表.xlsx');
            findCustomersPages_api()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion
</script>

<style scoped lang='scss'>
.map_input {
    width: 100%;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.div_bg:hover {
    background-color: darkgray;
}
</style>

<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}


.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
